package com.vf.cloud.pass.mvc.sys.controller;

import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.jfinal.kit.StrKit;
import com.vf.cloud.pass.common.datasource.annotation.Tx;
import com.vf.cloud.pass.common.domain.sys.Dept;
import com.vf.cloud.pass.common.util.DateUtil;
import com.vf.cloud.pass.common.util.R;
import com.vf.cloud.pass.common.util.UuidUtil;

@RestController
@RequestMapping("/sys/dept")
public class DeptController {

	@GetMapping("/findList")
	public R<List<Dept>> findList(
			@RequestParam(name = "name" ,required = false) String name,
			@RequestParam(name = "code",required = false) String code,
			@RequestParam(name = "status",required = false) String status,
			@RequestParam(name = "rootId",required = false) String rootId) {
		List<Dept> depts = Dept.dao.list(name,code,status,rootId);
		return R.ok(depts);
	}

	@Tx
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<Dept> save(Dept dept) {
		try {
			if (StrKit.isBlank(dept.getName())) {
				return R.failed("名称不可以为空！");
			}
			
			//SimpleUser simpleUser=SecurityUtils.getUser();
			
			if (StrKit.notBlank(dept.getId())) {
//				if(simpleUser!=null) {
//					dept.setUpdateBy(simpleUser.getUsername());
//				}
				dept.setUpdateTime(DateUtil.getLocalDateTime());
				if (dept.update()) {
					return R.ok(dept);
				} else {
					return R.failed("更新失败！");
				}
			} else {
				dept.setId(UuidUtil.getUUID());
//				if(simpleUser!=null) {
//					dept.setCreateBy(simpleUser.getUsername());
//				}
				dept.setCreateTime(DateUtil.getLocalDateTime());
				if (StrKit.isBlank(dept.getParentId()))
					dept.setParentId("0");
				if (dept.save()) {
					return R.ok(dept);
				} else {
					return R.failed("保存失败！");
				}
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@Tx
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public R<String> delete(@RequestParam(name = "id") String id) throws Exception {
		try {
			if (StrKit.equals(id, "101")) {
				return R.failed("系统默认项不可以删除!");
			}
			if (!Dept.dao.hasChild(id)) {
				Dept dept = Dept.dao.findById(id);
				if (dept != null) {
					if (dept.delete()) {
						return R.ok();
					} else {
						return R.failed("删除失败！");
					}
				} else {
					return R.failed("数据不存在,请刷新后再试!");
				}
			} else {
				return R.failed("有子节点,不允许删除!");
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@RequestMapping(value = "/getOptionsTree", method = RequestMethod.GET)
	public R<List<Dept>> getOptionsTree() {
		return R.ok(Dept.dao.getTree("0"));
	}
}
